import Vue from 'vue'
import VueRouter from 'vue-router'

import logo from '@/views/user/logo.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qe from '@/views/qe/qe.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'
import sentud from '@/views/user/sentud.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'


Vue.use(VueRouter)

const routes = [
  {
    name: 'logo',
    path: '/logo',
    component: logo,
    meta: {showTop:true}
  },
  {
    name: 'home',
    path: '/home',
    component: home,
    meta: {showTab:true}
    
  },
  {
    name: 'movie',
    path: '/movie',
    component: movie,
    meta: {showTab:true}
    
  },
  {
    name: 'qe',
    path: '/qe',
    component: qe,
    meta: {showTab:true}
    
  },
  {
    name: 'user',
    path: '/user',
    component: user,
    meta: {showTab:true,isLogin:true}
    
  },
  {
    path: '/notfound',
    component: notfound,
    meta: {showTab:true}
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'sentud',
    path: '/sentud',
    component: sentud
  },
  {
    name: 'myarticle',
    path: '/article',
    component:article,
  },
  {
    name: 'search',
    path: '/search',
    component:search,
  },
  //首页重定向,如果路径是/,则重定向到home
  //默认跳转首页
  {
    path: '/',
    redirect: '/home'
  },
  //错误跳转路径404
  {
    path: '*',
    redirect: '/notfound'
  }

]
/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
//(1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

//导入token工具包
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant';

// // 注册导航守卫 (全局前置守卫  跳转之前执行)
// router.beforeEach((to, from, next) => {
//   //判断用户没有没有登录
//   if (to.meta.isLogin && !getToken()) {
//     /* this.$toast只能在组件里面使用,全局使用直接Toast即可（官网文档有介绍） */
//     Toast.fail('请先登录')
//     //没有登录，则跳转登录页
//     next({ path: '/logo'})
//   } else {
//     //有登录，正常跳转
//     next()
//   }
// })
//注册导航守卫(全局前置守卫  跳转之前执行)
router.beforeEach((to, from, next) => {
  //判断用户有没有登录
  if (to.meta.isLogin && !getToken()) {
    // this.$toast只能在组件里面使用,全局使用直接Toast即可(管网文档有介绍)
    Toast.fail('请先登录')
    //没有登录,则跳转登录页面
    next({path:'/logo'})
  } else {
    // 没有正常登录,则跳转登录页面
    next()
  }
})



export default router
